<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="模块化模式">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2019-08-16-module-pattern/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="og:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/0008.jpg">
  <meta property="article:published_time" content="2019-08-16T12:26:46.000Z">
  <meta property="article:modified_time" content="2019-08-16T12:26:46.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="JavaScript">
  <meta property="article:tag" content="闭包">
  <meta property="article:tag" content="模块">
  <meta name="twitter:card" content="summary">
  <meta name="twitter:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2019-08-16-module-pattern/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>模块化模式 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9A%84%E5%8F%91%E5%B1%95"><span class="nav-number">1.</span> <span class="nav-text">模块化的发展</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9D%E5%AD%A6%E8%80%85%E7%9A%84%E4%BB%A3%E7%A0%81-%E5%8E%9F%E5%A7%8B%E5%86%99%E6%B3%95"><span class="nav-number">1.1.</span> <span class="nav-text">初学者的代码 - 原始写法</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%AB%98%E7%BA%A7%E4%B8%80%E7%82%B9%E7%9A%84%E4%BB%A3%E7%A0%81-%E5%AF%B9%E8%B1%A1%E5%86%99%E6%B3%95"><span class="nav-number">1.2.</span> <span class="nav-text">高级一点的代码 - 对象写法</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9D%E5%85%B7%E6%A0%B7%E5%AD%90%E7%9A%84%E4%BB%A3%E7%A0%81-%E9%97%AD%E5%8C%85%E5%86%99%E6%B3%95"><span class="nav-number">1.3.</span> <span class="nav-text">初具样子的代码 - 闭包写法</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%86%8D%E6%AC%A1%E5%8D%87%E7%BA%A7-IIFE%E5%86%99%E6%B3%95"><span class="nav-number">1.4.</span> <span class="nav-text">再次升级 - IIFE写法</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A8%A1%E5%9D%97%E7%9A%84%E7%BB%A7%E6%89%BF"><span class="nav-number">1.5.</span> <span class="nav-text">模块的继承</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A8%A1%E5%9D%97%E9%97%B4%E7%9A%84%E7%9B%B8%E4%BA%92%E5%BC%95%E7%94%A8"><span class="nav-number">1.6.</span> <span class="nav-text">模块间的相互引用</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#ES6%E6%A8%A1%E5%9D%97"><span class="nav-number">2.</span> <span class="nav-text">ES6模块</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BA%94%E7%94%A8"><span class="nav-number">2.1.</span> <span class="nav-text">应用</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9C%A8%E6%B5%8F%E8%A7%88%E5%99%A8%E4%B8%8A%E7%9B%B4%E6%8E%A5%E4%BD%BF%E7%94%A8ES6%E6%A8%A1%E5%9D%97"><span class="nav-number">2.2.</span> <span class="nav-text">在浏览器上直接使用ES6模块</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%87%E6%B8%A1%E9%98%B6%E6%AE%B5%E7%9A%84%E6%A8%A1%E5%9D%97"><span class="nav-number">3.</span> <span class="nav-text">过渡阶段的模块</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="nav-number">3.1.</span> <span class="nav-text">实现原理</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#Commonjs"><span class="nav-number">3.2.</span> <span class="nav-text">Commonjs</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#AMD"><span class="nav-number">3.3.</span> <span class="nav-text">AMD</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#CMD"><span class="nav-number">3.4.</span> <span class="nav-text">CMD</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%B0%E5%BA%95%E5%93%AA%E4%B8%AA%E5%A5%BD%E7%94%A8"><span class="nav-number">3.5.</span> <span class="nav-text">到底哪个好用</span></a></li>
                    </ol>
                  </li>
                </ol>
                </li>
                <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number"></span> <span class="nav-text">参考</span></a>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2019-08-16-module-pattern/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              模块化模式
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2019-08-16 20:26:46" itemprop="dateCreated datePublished" datetime="2019-08-16T20:26:46+08:00">2019-08-16</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                  </span>
                </span>


                <span id="/blob/2019-08-16-module-pattern/" class="post-meta-item leancloud_visitors" data-flag-title="模块化模式" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <p><a target="_blank" rel="noopener" href="https://github.com/jwenjian/visitor-count-badge"><img src="" data-original="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/" alt="总访客数量"></a></p>
            <p>模块是闭包最强大的一种应用，在团队开发中是迫切需要的，可以更好的划分团队人员职能，做到精细化管理而互不干扰。</p>
            <h2 id="模块化的发展"><a href="#模块化的发展" class="headerlink" title="模块化的发展"></a>模块化的发展</h2>
            <h3 id="初学者的代码-原始写法"><a href="#初学者的代码-原始写法" class="headerlink" title="初学者的代码 - 原始写法"></a>初学者的代码 - 原始写法</h3>
            <p>作为一名初学者，写代码可能是一堆一堆的，所以为了好看一点，就把这一段代码包含在一个函数里面以供调用。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">m1</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="comment">//...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">m2</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="comment">//...</span></span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>上面的函数m1()和m2()，组成一个模块。使用的时候，直接调用就行了。</p>
            <p>缺点是污染了全局变量，容易照成变量名冲突，各模块直接关系混乱。</p>
            <p>如果代码都是大段大段的，最后导致写成了一堆无人能看懂的代码。</p>
            <h3 id="高级一点的代码-对象写法"><a href="#高级一点的代码-对象写法" class="headerlink" title="高级一点的代码 - 对象写法"></a>高级一点的代码 - 对象写法</h3>
            <p>所以就有人使用对象的写法</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> module1 = &#123;</span><br><span class="line"></span><br><span class="line">  _count : <span class="number">0</span>,</span><br><span class="line"></span><br><span class="line">  m1 : <span class="function"><span class="keyword">function</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  m2 : <span class="function"><span class="keyword">function</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>上面的函数m1()和m2(），都封装在module1对象里。使用的时候，就是调用这个对象的属性。</p>
            <p>但是，这样的写法会暴露所有模块成员，内部状态可以被外部改写。比如，外部代码可以直接改变内部计数器的值。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">module1._count = <span class="number">5</span>;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h3 id="初具样子的代码-闭包写法"><a href="#初具样子的代码-闭包写法" class="headerlink" title="初具样子的代码 - 闭包写法"></a>初具样子的代码 - 闭包写法</h3>
            <p>所以闭包来了，可以做到变量的私有化</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">CoolModule</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> something = <span class="string">&quot;cool&quot;</span>;</span><br><span class="line">  <span class="keyword">var</span> another = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">doSomething</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log( something );</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">doAnother</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log( another.join( <span class="string">&quot; ! &quot;</span> ) );</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    doSomething: doSomething,</span><br><span class="line">    doAnother: doAnother</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> foo = CoolModule();</span><br><span class="line"></span><br><span class="line">foo.doSomething(); <span class="comment">// cool</span></span><br><span class="line">foo.doAnother(); <span class="comment">// 1 ! 2 ! 3</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>使用上面的写法，外部代码无法读取内部的something、another变量。</p>
            <p>首先，<code>CoolModule()</code> 只是一个函数，但它 <em>必须被调用</em> 才能成为一个被创建的‘模块实例’（我们暂且叫<code>foo</code>为‘模块实例’或者‘实例’）。</p>
            <p>第二，<code>CoolModule()</code> 函数返回一个对象。这个返回的对象拥有指向内部函数的引用，但是 <em>没有</em> 指向内部数据变量的引用；也可以看做是<strong>模块的公有API</strong>。我们也可以仅仅返回一个内部函数，<code>jQuery</code> 就是一个很好地例子。</p>
            <p>这个返回值对象最终被赋值给外部变量 <code>foo</code>，然后我们可以在这个API上访问那些属性，比如 <code>foo.doSomething()</code>。</p>
            <p><code>doSomething()</code> 和 <code>doAnother()</code> 函数拥有模块“实例”内部作用域的闭包，也就是说<code>foo</code>拥有了访问模块词法作用域的能力。</p>
            <p>这种方式可以可以重复创建多个‘实例’，如果想仅仅创建一个‘实例’，就要使用<code>IIFE</code>。</p>
            <h3 id="再次升级-IIFE写法"><a href="#再次升级-IIFE写法" class="headerlink" title="再次升级 - IIFE写法"></a>再次升级 - IIFE写法</h3>
            <p>所以立即调用函数表达式来了，做到了在代码加载成功之后自动创建一个‘实例’，并且不会再次创建一个新的‘实例’；因为没有同样的‘实例’，所以这个‘实例’是‘单例’的。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> foo = (<span class="function"><span class="keyword">function</span> <span class="title">CoolModule</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> something = <span class="string">&quot;cool&quot;</span>;</span><br><span class="line">  <span class="keyword">var</span> another = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">doSomething</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log( something );</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">doAnother</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log( another.join( <span class="string">&quot; ! &quot;</span> ) );</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    doSomething: doSomething,</span><br><span class="line">    doAnother: doAnother</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br><span class="line">foo.doSomething(); <span class="comment">// cool</span></span><br><span class="line">foo.doAnother(); <span class="comment">// 1 ! 2 ! 3</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>


            <h3 id="模块的继承"><a href="#模块的继承" class="headerlink" title="模块的继承"></a>模块的继承</h3>
            <p>如果一个模块很大要分成几个部分，或者要继承另一个模块，这是就要采用下面这种方式，同时最后一行的<code>module1 || &#123;&#125;</code>是必须的，防止浏览器异步加载导致的引用错误。</p>
            <p>而且这样的好处是和外界完全隔离，也不需要在作用域链上进行疯狂的查找。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> module1 = (<span class="function"><span class="keyword">function</span> (<span class="params">mod</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">  mod.m3 = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> mod;</span><br><span class="line"></span><br><span class="line">&#125;)(module1 || &#123;&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h3 id="模块间的相互引用"><a href="#模块间的相互引用" class="headerlink" title="模块间的相互引用"></a>模块间的相互引用</h3>
            <p>模块间的相互引用也是没有问题的，只是写法有点特殊。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">// 1. 首先注册模块实例</span></span><br><span class="line"><span class="keyword">var</span> module1 = &#123;&#125;;</span><br><span class="line"><span class="keyword">var</span> module2 = &#123;&#125;;</span><br><span class="line"><span class="comment">// 2. 实现模块实例</span></span><br><span class="line">module1 = (<span class="function"><span class="keyword">function</span> (<span class="params">mod1, mod2</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">  mod1.m1 = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;--module1--&#x27;</span>);</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  mod1.m2 = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> mod2.m1()</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> mod1;</span><br><span class="line"></span><br><span class="line">&#125;)(module1 || &#123;&#125;, module2 || &#123;&#125;);</span><br><span class="line"></span><br><span class="line">module2 = (<span class="function"><span class="keyword">function</span> (<span class="params">mod1, mod2</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">  mod2.m1 = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;--module2--&#x27;</span>);</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  mod2.m2 = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> mod1.m1()</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> mod2;</span><br><span class="line"></span><br><span class="line">&#125;)(module1 || &#123;&#125;, module2 || &#123;&#125;);</span><br><span class="line"><span class="comment">// 3. 调用模块实例方法</span></span><br><span class="line">module1.m2() <span class="comment">// --module2--</span></span><br><span class="line">module2.m2() <span class="comment">// --module1--</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这里要注意的是要先注册模块实例，然后再实现各模块实例，最后要在全部模块加载完代码之后再执行即可。</p>
            <h2 id="ES6模块"><a href="#ES6模块" class="headerlink" title="ES6模块"></a>ES6模块</h2>
            <p>ES6 引入了模块化，其设计思想是在编译时就能确定模块的依赖关系，以及输入和输出的变量。ES6 <code>模块</code>必须被定义在一个分离的文件中（每个模块一个）。浏览器/引擎拥有一个默认的“模块加载器”，它在模块被导入时同步地加载模块文件。</p>
            <p>ES6 的模块化分为导出（<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/export">export</a>） @与导入（<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/import">import</a>）两个模块。</p>
            <p>ES6 的模块自动开启严格模式，不管你有没有在模块头部加上 <code>use strict;</code>。</p>
            <p>模块中可以导入和导出各种类型的变量，如函数，对象，字符串，数字，布尔值，类等。</p>
            <p>每个模块都有自己的上下文，每一个模块内声明的变量都是局部变量，不会污染全局作用域。</p>
            <p>每一个模块只加载一次（是单例的）， 若再去加载同目录下同文件，直接从内存中读取。</p>
            <h3 id="应用"><a href="#应用" class="headerlink" title="应用"></a>应用</h3>
            <p><strong>bar.js</strong></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hello</span>(<span class="params">who</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="string">&quot;Let me introduce: &quot;</span> + who;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> hello;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><strong>foo.js</strong></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">// 导入“bar”模块中的`hello()`</span></span><br><span class="line"><span class="keyword">import</span> hello <span class="keyword">from</span> <span class="string">&quot;bar&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> hungry = <span class="string">&quot;hippo&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">awesome</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(</span><br><span class="line">    hello( hungry ).toUpperCase()</span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> awesome;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><strong>app.js</strong></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">// 导入`foo`和`bar`整个模块</span></span><br><span class="line"><span class="built_in">module</span> foo <span class="keyword">from</span> <span class="string">&quot;foo&quot;</span>;</span><br><span class="line"><span class="built_in">module</span> bar <span class="keyword">from</span> <span class="string">&quot;bar&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(</span><br><span class="line">	bar.hello( <span class="string">&quot;rhino&quot;</span> )</span><br><span class="line">); <span class="comment">// Let me introduce: rhino</span></span><br><span class="line"></span><br><span class="line">foo.awesome(); <span class="comment">// LET ME INTRODUCE: HIPPO</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h3 id="在浏览器上直接使用ES6模块"><a href="#在浏览器上直接使用ES6模块" class="headerlink" title="在浏览器上直接使用ES6模块"></a>在浏览器上直接使用ES6模块</h3>
            <p><strong>module “my-module.js”</strong></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">cube</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> x * x * x;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> cube;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><strong>script demo.js</strong></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">import</span> &#123; cube &#125; <span class="keyword">from</span> <span class="string">&#x27;my-module.js&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(cube(<span class="number">3</span>)); <span class="comment">// 27</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><strong>html</strong></p>
            <figure class="highlight html">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;module&quot;</span> <span class="attr">src</span>=<span class="string">&quot;./demo.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="过渡阶段的模块"><a href="#过渡阶段的模块" class="headerlink" title="过渡阶段的模块"></a>过渡阶段的模块</h2>
            <p>在ES6模块未出现之前出现了一些大家公认的模块规范，首先来看一个简单的例子，并了解实现原理。然后再了解其他的模块规范。</p>
            <p>目前，通行的js模块规范主要有两种：CommonJS和AMD。</p>
            <h3 id="实现原理"><a href="#实现原理" class="headerlink" title="实现原理"></a>实现原理</h3>
            <p>模块依赖加载器/消息机制实质上都是将这种模块定义包装进一个友好的API。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> MyModules = (<span class="function"><span class="keyword">function</span> <span class="title">Manager</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> modules = &#123;&#125;;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">define</span>(<span class="params">name, deps, impl</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>; i&lt;deps.length; i++) &#123;</span><br><span class="line">      deps[i] = modules[deps[i]];</span><br><span class="line">    &#125;</span><br><span class="line">    modules[name] = impl.apply( impl, deps );</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> modules[name];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    define: define,</span><br><span class="line">    get: get</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;)();</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这段代码的关键部分是 <code>modules[name] = impl.apply(impl, deps)</code>。这为一个模块调用了它的定义的包装函数（传入所有依赖），并将返回值，也就是模块的API，存储到一个用名称追踪的内部模块列表中。</p>
            <p>这里是我可能如何使用它来定义一个模块：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">MyModules.define( <span class="string">&quot;bar&quot;</span>, [], <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">hello</span>(<span class="params">who</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;Let me introduce: &quot;</span> + who;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    hello: hello</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">MyModules.define( <span class="string">&quot;foo&quot;</span>, [<span class="string">&quot;bar&quot;</span>], <span class="function"><span class="keyword">function</span>(<span class="params">bar</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> hungry = <span class="string">&quot;hippo&quot;</span>;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">awesome</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log( bar.hello( hungry ).toUpperCase() );</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    awesome: awesome</span><br><span class="line">  &#125;;</span><br><span class="line">&#125; );</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = MyModules.get( <span class="string">&quot;bar&quot;</span> );</span><br><span class="line"><span class="keyword">var</span> foo = MyModules.get( <span class="string">&quot;foo&quot;</span> );</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(</span><br><span class="line">  bar.hello( <span class="string">&quot;hippo&quot;</span> )</span><br><span class="line">); <span class="comment">// Let me introduce: hippo</span></span><br><span class="line"></span><br><span class="line">foo.awesome(); <span class="comment">// LET ME INTRODUCE: HIPPO</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>模块“foo”和“bar”都使用一个返回公有API的函数来定义。“foo”甚至接收一个“bar”的实例作为依赖参数，并且可以因此使用它。</p>
            <p>它们只是满足了模块模式的两个性质：调用一个函数定义包装器，并将它的返回值作为这个模块的API保存下来。</p>
            <h3 id="Commonjs"><a href="#Commonjs" class="headerlink" title="Commonjs"></a>Commonjs</h3>
            <p>2009年，美国程序员Ryan Dahl创造了<a target="_blank" rel="noopener" href="http://nodejs.org/">node.js</a>项目，将javascript语言用于服务器端编程。</p>
            <p><img src="" data-original="/images/FrontEnd/0008.jpg" alt="img"></p>
            <p>这标志”Javascript模块化编程”正式诞生。因为老实说，在浏览器环境下，没有模块也不是特别大的问题，毕竟网页程序的复杂性有限；但是在服务器端，一定要有模块，与操作系统和其他应用程序互动，否则根本没法编程。</p>
            <p>node.js的<a target="_blank" rel="noopener" href="http://nodejs.org/docs/latest/api/modules.html">模块系统</a>，就是参照<a target="_blank" rel="noopener" href="http://wiki.commonjs.org/wiki/Modules/1.1">CommonJS</a>规范实现的。在CommonJS中，有一个全局性方法require()，用于加载模块。假定有一个数学模块math.js，就可以像下面这样加载。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> math = <span class="built_in">require</span>(<span class="string">&#x27;math&#x27;</span>);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>然后，就可以调用模块提供的方法：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> math = <span class="built_in">require</span>(<span class="string">&#x27;math&#x27;</span>);</span><br><span class="line">math.add(<span class="number">2</span>,<span class="number">3</span>); <span class="comment">// 5</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>因为这个系列主要针对浏览器编程，不涉及node.js，所以对CommonJS就不多做介绍了。我们在这里只要知道，require()用于加载模块就行了。</p>
            <h3 id="AMD"><a href="#AMD" class="headerlink" title="AMD"></a>AMD</h3>
            <p>CommonJS规范不适用于浏览器环境，如果在浏览器中运行，会有一个很大的问题。</p>
            <p>服务器端因为所有的模块都存放在本地硬盘，可以同步加载完成，等待时间就是硬盘的读取时间。但是，对于浏览器，这却是一个大问题，因为模块都放在服务器端，等待时间取决于网速的快慢，可能要等很长时间，浏览器处于”假死”状态，导致后面的代码不能继续执行。</p>
            <p>因此采用”异步加载”（asynchronous），这就是AMD规范诞生的背景。</p>
            <p><a target="_blank" rel="noopener" href="https://github.com/amdjs/amdjs-api/wiki/AMD-(%E4%B8%AD%E6%96%87%E7%89%88)">AMD</a>是”Asynchronous Module Definition”的缩写，意思就是”异步模块定义”。它采用异步方式加载模块，模块的加载不影响它后面语句的运行。所有依赖这个模块的语句，都定义在一个回调函数中，等到加载完成之后，这个回调函数才会运行。</p>
            <h4 id="define-函数"><a href="#define-函数" class="headerlink" title="define() 函数"></a>define() 函数</h4>
            <p>本规范只定义了一个函数 “define”，它是全局变量。函数的描述为：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">define(id?, dependencies?, factory);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <ol>
              <li>第一个参数，id - 名字：<br>是个字符串。它指的是定义中模块的名字，这个参数是可选的。如果没有提供该参数，模块的名字应该默认为模块加载器请求的指定脚本的名字。</li>
              <li>第二个参数，dependencies - 依赖：<br>是个定义中模块所依赖模块的数组。依赖模块必须根据模块的工厂方法优先级执行，并且执行的结果应该按照依赖数组中的位置顺序以参数的形式传入（定义中模块的）工厂方法中。<br>本规范定义了三种特殊的依赖关键字。如果”require”,”exports”, 或 “module”出现在依赖列表中，参数应该按照CommonJS模块规范自由变量去解析。</li>
              <li>第三个参数，factory - 工厂方法：<br>为模块初始化要执行的函数或对象。如果为函数，它应该只被执行一次。如果是对象，此对象应该为模块的输出值。</li>
            </ol>
            <h4 id="define-amd-属性"><a href="#define-amd-属性" class="headerlink" title="define.amd 属性"></a>define.amd 属性</h4>
            <p>为了清晰的标识全局函数（为浏览器加载script必须的）遵从AMD编程接口，任何全局函数应该有一个”amd”的属性，它的值为一个对象。这样可以防止与现有的定义了define函数但不遵从AMD编程接口的代码相冲突。</p>
            <h4 id="举例说明"><a href="#举例说明" class="headerlink" title="举例说明"></a>举例说明</h4>
            <p>创建一个名为”alpha”的模块，使用了require，exports，和名为”beta”的模块:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">define(<span class="string">&quot;alpha&quot;</span>, [<span class="string">&quot;require&quot;</span>, <span class="string">&quot;exports&quot;</span>, <span class="string">&quot;beta&quot;</span>], <span class="function"><span class="keyword">function</span> (<span class="params"><span class="built_in">require</span>, <span class="built_in">exports</span>, beta</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">exports</span>.verb = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> beta.verb();</span><br><span class="line">    <span class="comment">//Or:</span></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">require</span>(<span class="string">&quot;beta&quot;</span>).verb();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>一个使用了简单CommonJS转换的模块定义：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">define(<span class="function"><span class="keyword">function</span> (<span class="params"><span class="built_in">require</span>, <span class="built_in">exports</span>, <span class="built_in">module</span></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> a = <span class="built_in">require</span>(<span class="string">&#x27;a&#x27;</span>),</span><br><span class="line">      b = <span class="built_in">require</span>(<span class="string">&#x27;b&#x27;</span>);</span><br><span class="line"></span><br><span class="line">  <span class="built_in">exports</span>.action = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;;</span><br><span class="line">&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h4 id="RequireJS"><a href="#RequireJS" class="headerlink" title="RequireJS"></a>RequireJS</h4>
            <p>有人说 AMD 是 RequireJS 在推广过程中对模块定义的规范化的产出，这一点没有深入的探究是否正确，但是根据AMD出现的原因，个人感觉是正确的。</p>
            <p><a target="_blank" rel="noopener" href="https://requirejs.org/">RequireJS</a> 是实现AMD规范的一个非常流行的库。使用前先去 <a target="_blank" rel="noopener" href="https://requirejs.org/docs/download.html">官方网站下载</a> 最新版本。</p>
            <figure class="highlight html">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">&lt;!-- async 属性表明这个文件需要异步加载，避免网页失去响应。IE不支持这个属性，只支持defer，所以把defer也写上 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;js/require.js&quot;</span> <span class="attr">defer</span> <span class="attr">async</span>=<span class="string">&quot;true&quot;</span> &gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- data-main 属性的作用是，指定网页程序的主模块 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;js/require.js&quot;</span> <span class="attr">data-main</span>=<span class="string">&quot;js/main&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h5 id="主模块写法"><a href="#主模块写法" class="headerlink" title="主模块写法"></a>主模块写法</h5>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="built_in">require</span>([<span class="string">&#x27;jquery&#x27;</span>, <span class="string">&#x27;underscore&#x27;</span>, <span class="string">&#x27;backbone&#x27;</span>], <span class="function"><span class="keyword">function</span> (<span class="params">$, _, Backbone</span>)</span>&#123;</span><br><span class="line">  <span class="comment">// some code here</span></span><br><span class="line">&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>or</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">define([<span class="string">&#x27;jquery&#x27;</span>, <span class="string">&#x27;underscore&#x27;</span>, <span class="string">&#x27;backbone&#x27;</span>], <span class="function"><span class="keyword">function</span> (<span class="params">$, _, Backbone</span>)</span>&#123;</span><br><span class="line">  <span class="comment">// some code here</span></span><br><span class="line">&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>子模块的写法也是一样的。</p>
            <h5 id="自定义模块加载行为"><a href="#自定义模块加载行为" class="headerlink" title="自定义模块加载行为"></a>自定义模块加载行为</h5>
            <p>自定义模块加载行为通过 <code>require.config()</code> 实现，写在主模块的头部。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="built_in">require</span>.config(&#123;</span><br><span class="line">  <span class="comment">// 改变基目录</span></span><br><span class="line">  baseUrl: <span class="string">&quot;js/lib&quot;</span>,</span><br><span class="line">  <span class="comment">// 指定各个模块的加载路径</span></span><br><span class="line">  paths: &#123;</span><br><span class="line">    <span class="comment">// 直接指定网址</span></span><br><span class="line">    <span class="string">&quot;jquery&quot;</span>: <span class="string">&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min&quot;</span></span><br><span class="line">    <span class="string">&quot;underscore&quot;</span>: <span class="string">&quot;underscore.min&quot;</span>,</span><br><span class="line">    <span class="string">&quot;backbone&quot;</span>: <span class="string">&quot;backbone.min&quot;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 加载非规范的模块。underscore和backbone这两个库，都没有采用AMD规范编写。</span></span><br><span class="line">  shim: &#123;</span><br><span class="line">    <span class="string">&#x27;underscore&#x27;</span>:&#123;</span><br><span class="line">      <span class="built_in">exports</span>: <span class="string">&#x27;_&#x27;</span>, <span class="comment">// 输出的变量名</span></span><br><span class="line">    &#125;,</span><br><span class="line"></span><br><span class="line">    <span class="string">&#x27;backbone&#x27;</span>: &#123;</span><br><span class="line">      deps: [<span class="string">&#x27;underscore&#x27;</span>, <span class="string">&#x27;jquery&#x27;</span>], <span class="comment">// 模块的依赖性</span></span><br><span class="line">      <span class="built_in">exports</span>: <span class="string">&#x27;Backbone&#x27;</span>, <span class="comment">// 输出的变量名</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>require.js要求，每个模块是一个单独的js文件。这样的话，如果加载多个模块，就会发出多次HTTP请求，会影响网页的加载速度。因此，require.js提供了一个<a target="_blank" rel="noopener" href="http://requirejs.org/docs/optimization.html">优化工具</a>，当模块部署完毕以后，可以用这个工具将多个模块合并在一个文件中，减少HTTP请求数。</p>
            <h5 id="插件"><a href="#插件" class="headerlink" title="插件"></a>插件</h5>
            <p><a target="_blank" rel="noopener" href="https://github.com/requirejs/requirejs/wiki/Plugins">RequireJS 插件</a> 实现了一些特定的功能。</p>
            <p>domready插件，可以让回调函数在页面DOM结构加载完成后再运行。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="built_in">require</span>([<span class="string">&#x27;domready!&#x27;</span>], <span class="function"><span class="keyword">function</span> (<span class="params">doc</span>)</span>&#123;</span><br><span class="line">  <span class="comment">// called once the DOM is ready</span></span><br><span class="line">&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>text和image插件，则是允许require.js加载文本和图片文件。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">define([</span><br><span class="line">  <span class="string">&#x27;text!review.txt&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;image!cat.jpg&#x27;</span></span><br><span class="line">  ],</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span>(<span class="params">review,cat</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(review);</span><br><span class="line">    <span class="built_in">document</span>.body.appendChild(cat);</span><br><span class="line">  &#125;</span><br><span class="line">);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>类似的插件还有json和mdown，用于加载json文件和markdown文件。</p>
            <h3 id="CMD"><a href="#CMD" class="headerlink" title="CMD"></a>CMD</h3>
            <p><a target="_blank" rel="noopener" href="https://github.com/cmdjs/specification/blob/master/draft/module.md">CMD</a> 模块规范是 <a target="_blank" rel="noopener" href="https://github.com/seajs/seajs">seajs</a> 推广的产物。</p>
            <p>区别于 AMD 的异步加载，CMD 规范是懒加载，在用的时候才加载，一个文件是一个模块</p>
            <h4 id="defined-函数"><a href="#defined-函数" class="headerlink" title="defined() 函数"></a>defined() 函数</h4>
            <p>模块定义使用 <code>define</code> 关键字的方法，并接收一个<code>factory</code>的方法</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">define(<span class="function"><span class="keyword">function</span>(<span class="params"><span class="built_in">require</span>, <span class="built_in">exports</span>, <span class="built_in">module</span></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 模块代码</span></span><br><span class="line">&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <ul>
              <li>define函数接受单个参数模块工厂。</li>
              <li>factory可以是一个函数或其他有效的值。</li>
              <li>如果factory是函数，则该函数的前三个参数（如果已指定）必须依次为<code>require</code> <code>exports</code> 和 <code>module</code>。</li>
              <li>如果factory不是函数，则将模块的导出设置为该对象。</li>
            </ul>
            <p>具体的用法可以查看 <a target="_blank" rel="noopener" href="https://github.com/cmdjs/specification/blob/master/draft/module.md">Common Module Definition / draft</a> <a target="_blank" rel="noopener" href="https://github.com/seajs/seajs/issues/242">CMD 模块定义规范</a></p>
            <h4 id="seajs"><a href="#seajs" class="headerlink" title="seajs"></a>seajs</h4>
            <p><a target="_blank" rel="noopener" href="https://github.com/seajs/seajs">seajs</a> 使用的是CMD模块规范，具体的使用方法请<a target="_blank" rel="noopener" href="https://seajs.github.io/seajs/docs/#intro">查看文档</a></p>
            <h3 id="到底哪个好用"><a href="#到底哪个好用" class="headerlink" title="到底哪个好用"></a>到底哪个好用</h3>
            <p>RequireJs 和 seajs 有什么区别，哪一个更好用，这个在现在已经9012了，很多人都在用ES6的模块，还讨论这个话题就是为了六个念想。</p>
            <p>前端为了减少请求次数都会打包到一个文件中，所以这两个就没什么区别。</p>
            <p>谁说不是呢。</p>
            <p>鉴于 RequireJs 应用更广泛，工程化更好，解决方案更多，推荐使用 RequireJs 。</p>
            <p>在下方参考中也有很多的讨论，可自行查看</p>
            <h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1>
            <p><a target="_blank" rel="noopener" href="https://github.com/holidaypenguin/You-Dont-Know-JS/blob/1ed-zh-CN/scope%20%26%20closures/ch5.md">你不懂JS：作用域与闭包</a><br><a target="_blank" rel="noopener" href="http://www.ruanyifeng.com/blog/2012/10/javascript_module.html">Javascript模块化编程（一）：模块的写法</a><br><a target="_blank" rel="noopener" href="http://www.ruanyifeng.com/blog/2012/10/asynchronous_module_definition.html">Javascript模块化编程（二）：AMD规范</a><br><a target="_blank" rel="noopener" href="http://www.ruanyifeng.com/blog/2012/11/require_js.html">Javascript模块化编程（三）：require.js的用法</a><br><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/export">export</a><br><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/import">import</a><br><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/87a7827b2d73">详解JavaScript模块化开发</a><br><a target="_blank" rel="noopener" href="http://wiki.commonjs.org/wiki/CommonJS">CommonJS</a><br><a target="_blank" rel="noopener" href="https://github.com/amdjs/amdjs-api/wiki/AMD-(%E4%B8%AD%E6%96%87%E7%89%88)">AMD (中文版)</a><br><a target="_blank" rel="noopener" href="https://github.com/amdjs/amdjs-api/wiki/require-(%E4%B8%AD%E6%96%87%E7%89%88)">require (中文版)</a><br><a target="_blank" rel="noopener" href="https://github.com/requirejs/requirejs">RequireJS</a><br><a target="_blank" rel="noopener" href="https://requirejs.org/docs/api.html#config-shim">config-shim</a><br><a target="_blank" rel="noopener" href="https://www.cnblogs.com/yexiaochai/p/3633855.html">【requireJS源码学习02】data-main加载的实现</a><br><a target="_blank" rel="noopener" href="https://github.com/requirejs/requirejs/wiki/Plugins">RequireJS 插件</a><br><a target="_blank" rel="noopener" href="https://github.com/seajs/seajs/issues/242">CMD 模块定义规范</a> <em>–感觉说地不对，最好看接下来的英文版</em><br><a target="_blank" rel="noopener" href="https://github.com/cmdjs/specification/blob/master/draft/module.md">CMD</a><br><a target="_blank" rel="noopener" href="https://github.com/seajs/seajs">seajs</a><br><a target="_blank" rel="noopener" href="https://github.com/seajs/seajs/issues/277">与 RequireJS 的异同</a><br><a target="_blank" rel="noopener" href="https://www.douban.com/note/283566440/">SeaJS与RequireJS最大的区别</a><br><a target="_blank" rel="noopener" href="https://www.zhihu.com/question/20342350">LABjs、RequireJS、SeaJS 哪个最好用？为什么？</a><br><a target="_blank" rel="noopener" href="https://www.zhihu.com/question/20351507/answer/14859415">AMD 和 CMD 的区别有哪些？</a></p>

          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
              <a href="/tags/%E9%97%AD%E5%8C%85/" rel="tag"># 闭包</a>
              <a href="/tags/%E6%A8%A1%E5%9D%97/" rel="tag"># 模块</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2019-08-08-summary-of-fiddler-packaging-tools/" rel="prev" title="Fiddler 抓包工具总结">
                  <i class="fa fa-chevron-left"></i> Fiddler 抓包工具总结
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2019-09-10-gulp-setup-deployment-environment/" rel="next" title="Gulp 设置部署环境">
                  Gulp 设置部署环境 <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>